const http = require("../../../utils/https");
// 获取小程序全局实例
const app = getApp();

Page({
  data: {
    amount: '0.00',      // 支付金额（由上个页面传递）
    scene: '',           // 支付场景：recharge | bill | parking
    billId: '',          // 账单ID（从物业账单详情传递）
    payWay: '余额',      // 当前支付方式
    passwordArr: [],     // 已输入密码（存储●）
    loading: false,
    error: '',
    oweAmount:''
  },

  
  onLoad(options) {
    let incomingAmount = '0.00';
    if (options && options.amount) incomingAmount = options.amount;
    if (options && options.billId) this.setData({ billId: options.billId });
    if (options && options.oweAmount) this.setData({ oweAmount: options.oweAmount });

    // 事件通道（备用）
    try {
      const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
      if (eventChannel) {
        eventChannel.on && eventChannel.on('payAmount', data => {
          if (data && data.amount) {
            incomingAmount = data.amount;
            this.setData({ amount: this.formatAmount(incomingAmount) });
          }
        });
      }
    } catch (e) {}

    if (!incomingAmount || isNaN(Number(incomingAmount))) {
      const cached = wx.getStorageSync('lastPayAmount');
      if (cached) incomingAmount = cached;
    }

    this.setData({ amount: this.formatAmount(incomingAmount) });
    wx.setStorageSync('lastPayAmount', this.data.amount);
  },

  // 金额格式化
  formatAmount(val) {
    const n = Number(val || 0);
    return n.toFixed(2);
  },

  // 输入密码
  onInput(e) {
    if (this.data.passwordArr.length < 6) {
      this.setData({
        [`passwordArr[${this.data.passwordArr.length}]`]: '●'
      });
    }
  },

  // 删除密码
  onDelete() {
    if (this.data.passwordArr.length > 0) {
      this.data.passwordArr.pop();
      this.setData({ passwordArr: this.data.passwordArr });
    }
  },

  // 切换支付方式（示例）
  onChangePayWay() {
    wx.showActionSheet({
      itemList: ['余额', '银行卡', '微信支付'],
      success: (res) => {
        this.setData({ payWay: ['余额', '银行卡', '微信支付'][res.tapIndex] });
      }
    });
  },

  // 确认支付
  onPay() {
    if (this.data.passwordArr.length !== 6) return;

    wx.showLoading({ title: '支付中...' });
    
    const onLocalSuccess = () => {
      wx.hideLoading();
      wx.showToast({ title: '支付成功' });
      wx.setStorageSync('paymentSuccess', true);
      wx.redirectTo({ url: `/service/pages/paysuccess/paysuccess?amount=${this.data.amount}` });
    };

    
    // 充值场景：调用充值接口
      
    const residentId = (app && app.globalData && app.globalData.residentId) || '';
    http.put('balance/balance/payment', { 
      residentId,
      balance: Number(this.data.amount)-Number(this.data.oweAmount),
    }).then(() => {
      onLocalSuccess();
    }).catch(err => {
      wx.hideLoading();
      console.error('充值失败:', err);
      wx.showToast({ title: (err && err.msg) || '充值失败，请重试', icon: 'none' });
    });

    // 账单场景：如果有 billId，优先更新物业账单状态
    if (this.data.billId) {
      this.updateBillStatus(this.data.billId)
        .then(onLocalSuccess)
        .catch(err => {
          console.error('更新账单状态失败，继续本地成功流程:', err);
          onLocalSuccess();
        });
      return;
    }

 
  },

  // 调用接口修改物业账单状态
  updateBillStatus(billId) {
    return http.put('bilManagement/bilManagement', {
      id: billId,
      paymentStatus: 1
    });
  },

  // 调用接口修改停车订单缴费状态（保留原逻辑）
  updatePaymentStatus(orderId) {
    return http.put('parkingPay/parkingPay', {
      id: orderId,
      paymentStatus: 0
    });
  },

  // 关闭弹窗
  onClose() { wx.navigateBack(); },
  onMaskTap() { this.onClose(); },
  preventTap() {}
});